#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
//#include <linux/sched.h>	// mm_struct
//#include <linux/mm_types.h>
//#include <linux/cgroup.h>
#include <linux/unistd.h>
#include <asm-generic/syscall.h>
//#include <unistd.h>
//#include <stdio.h>
#include <linux/syscalls.h>	// sys_close
#include <linux/errno.h>
//#include <asm/unistd_32.h>
//#include <linux/unistd.h>
//#include <asm-generic/unistd.h>
#include <asm-generic/errno.h>
#include <asm-generic/errno-base.h>
#include <linux/fs.h>

#ifndef __KERNEL__
#include <sys/stat.h>
#endif
//#include <sys/types.h>


MODULE_LICENSE("GPL");
MODULE_AUTHOR("Quentin");
MODULE_DESCRIPTION("TCPSERVER");

static unsigned long** getSysCallTable()
{
  unsigned long int	ptr = PAGE_OFFSET;
  unsigned long**	syscalltable;

  while (ptr < ULLONG_MAX)
    {
      syscalltable = (unsigned long**)ptr;
      if (syscalltable[__NR_close] == (unsigned long*)sys_close)
	return syscalltable;
      ptr += sizeof(unsigned long*);
    }
  return NULL;
}

typedef ssize_t (*writefct)(int fd, const void *buf, size_t count);
typedef int (*mkdfct)(const char *pathname, mode_t mode);

int init_module(void)
{
  unsigned long**	sct;
  writefct		fptr;
  mkdfct		mfct;
  char			c = 'A';

  printk("--- Loading custom module ---");
  if ((sct = getSysCallTable()) != NULL)
    {
      printk(KERN_INFO "sys_call_table base found at: %x\n[", sct);
      fptr = (writefct)sct[__NR_write];
      fptr(1, &c, 1);
      mfct = (mkdfct)sct[__NR_mkdir];
      if (syscall(__NR_mkdir, "/home/blop/NEW_DIRECTORY_SYSCALL", 0755) != 0)
	printk(KERN_INFO "ERROR-de-mkdir%d\n", syscall(__NR_mkdir, "/home/blop/NEW_DIRECTORY_SYSCALL", 0755));
      if (mfct("/home/blop/NEW_DIRECTORY_RECOVERED_SYSCALL", 0755) != 0)
	printk(KERN_INFO "ERROR-de-mkdir%d\n", mfct("/home/blop/NEW_DIRECTORY_RECOVERED_SYSCALL", 0755));
      else
	printk(KERN_INFO "SUCCESS-de-mkdir\n");
      printk(KERN_INFO "]\nend_test\n");
    }
  else
    printk(KERN_INFO "sys_call_table base NOT FOUND\n");
  return 0;
}

void            cleanup_module()
{
  printk("---Unloading custom module---\n");
}
